/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2012
 */


package com.smg.community.controller;

import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.Writer;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javacommon.base.BaseRestSpringController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.org.rapid_framework.page.Page;

import com.google.gson.Gson;
import com.smg.community.model.CrmRole;
import com.smg.community.model.CrmUser;
import com.smg.community.service.CityManager;
import com.smg.community.setting.ProjectSetting;
import com.smg.community.util.IdentifyingCode;
import com.smg.community.vo.query.CrmRoleQuery;
import com.smg.community.vo.query.CrmUserQuery;

/**
 * @author badqiu email:badqiu(a)gmail.com
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping("/crmuser")
public class CrmUserController extends BaseRestSpringController<CrmUser,java.lang.Integer>{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@RequestMapping(value="/gotologin")
	public String gotoLogin(ModelMap model) throws Exception {
		return "login";
	}
	@RequestMapping(value="/ajax/login")
	public void loginForHewei(CrmUser crmUser,HttpServletRequest request,HttpServletResponse response){
		System.out.println(" ==========in ajaxlogin   ");
		CrmUser loginUser = crmUserManager.getCrmUserByNameAndPwd(crmUser.getUserName(),crmUser.getUserPass());
	//设置登录失效时间为2个小时
		request.getSession().setMaxInactiveInterval(2*60*60);
		System.out.println(" =========="+loginUser.getUserName()+"   ");
		request.getSession().setAttribute(ProjectSetting.SESSION_USER_KEY,loginUser);
	}
	//登录
	@RequestMapping(value="/login")
	public String login(CrmUser crmUser, HttpServletRequest request, ModelMap model){
		try {
			CrmUser loginUser = getLoginUser(request);
			if ( loginUser ==  null) {
				loginUser = crmUserManager.getCrmUserByNameAndPwd(crmUser.getUserName(),crmUser.getUserPass());
			}
			String menu = request.getParameter("menu") == null ? "" : request.getParameter("menu");
			if(null != loginUser){
				String roleIds = loginUser.getRoleIds();
				if (!"".equals(roleIds)) {
					roleIds = roleIds.substring(1,roleIds.length() - 1);
					CrmRoleQuery query = new CrmRoleQuery();
					query.setId(roleIds);
					query.setFlag(0);
					List<CrmRole> roleList = crmRoleManager.getBy(query);
					if(roleList.size() > 0){
						String msg = "您所拥有的 ";
						for(CrmRole role : roleList){
							msg += role.getName() + ",";
						}
						msg = msg.substring(0,msg.length() - 1) + " 角色已被禁用，详情请联系管理员";
						request.setAttribute("msg", msg);
					}
					request.getSession().setAttribute(ProjectSetting.SESSION_USER_RIGHT, crmRightManager.getAllRightByRoleId(roleIds,null));
				}
				//设置登录失效时间为2个小时
				request.getSession().setMaxInactiveInterval(2*60*60);
				request.getSession().setAttribute(ProjectSetting.SESSION_USER_KEY,loginUser);
				//更新用户登陆时间
				loginUser.setLastLoginTimeString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				//将用户的任务showflag更新为1
		//		int userId = loginUser.getId();
		//  暂时去掉这行代码 因为crm_task的查询和更新太过频繁 容易导致死锁 2012-8-10
		//		crmTaskManager.updateShowFlag(userId);
				crmUserManager.update(loginUser);
				if(roleIds == null || roleIds.equals("")){
					model.addAttribute("role","other");
					return  "sitemain";
				}
				// 判断登录用户的角色
				CrmRoleQuery query = new CrmRoleQuery();
				query.setId(roleIds);
				query.setFlag(1);
				List<CrmRole> roleList = crmRoleManager.getBy(query);
				String roleName = "";
				for(CrmRole  role: roleList){
					roleName = roleName + role.getName();
				}
				if(roleName.indexOf("GM")!=-1){
					model.addAttribute("role","gm");
				}else if(roleName.indexOf("BD主管")!=-1){
					model.addAttribute("role","bdmaster");
				}else if(roleName.indexOf("BD经理")!=-1){
					model.addAttribute("role","bdmaster");
				}else if(roleName.indexOf("运营")!=-1){
					model.addAttribute("role","yunying");
				}else{
					model.addAttribute("role","other");
				}
				if(roleName.equals("BD")){
					model.addAttribute("role","bd");
				}
				return "sitemain";
			}else{
				if(!menu.equals("top")){
					request.setAttribute("msg", "登陆失败,请检查用户名密码");
				}
				request.setAttribute("userName", crmUser.getUserName());
				return "login";
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", "登陆失败,请检查用户名密码");
			return "login";
		}
	}
	//登出
	@RequestMapping(value="/logout")
	public String logout(CrmUser crmUser, HttpServletRequest request, ModelMap model){
		if(null != (crmUser = getLoginUser(request))){
			request.setAttribute("userName", crmUser.getUserName());
		} 
		request.getSession().setMaxInactiveInterval(2*60*60);
		request.getSession().setAttribute(ProjectSetting.SESSION_USER_KEY,null);
		request.getSession().setAttribute(ProjectSetting.SESSION_USER_RIGHT,null);
		request.getSession().setAttribute("crm_userid",null);
		request.getSession().setAttribute("crm_username",null);
		return "login";
	}
	//生成验证码方法1(有干扰线、汉字等)
	@RequestMapping(value = "/pictureCheckCode")
	public void pictureCheckCode(ModelMap model,HttpServletRequest request,HttpServletResponse response) {
		IdentifyingCode idCode = new IdentifyingCode();
		BufferedImage image = new BufferedImage(idCode.getWidth() , idCode.getHeight() , BufferedImage.TYPE_INT_BGR);
		Graphics2D g = image.createGraphics();
		//定义字体样式
		Font myFont = new Font("黑体" , Font.BOLD , 16);
		//设置字体
		g.setFont(myFont);
		g.setColor(idCode.getRandomColor(200 , 250));
		//绘制背景
		g.fillRect(0, 0, idCode.getWidth() , idCode.getHeight());
		g.setColor(idCode.getRandomColor(180, 200));
		idCode.drawRandomLines(g, 160);
		String s = idCode.drawRandomString(4, g);
		request.getSession().setAttribute("piccode", s);
		g.dispose();
		try {
			ImageIO.write(image, "JPEG", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	//检查验证码是否相同（1是0否）
	//如果有2台以上服务器,可能会报空指针错误，所以要捕获该错误，将该错误当成验证码不相同处理
	@RequestMapping(value = "/checkCode")
	public void checkCode(ModelMap model,String code,HttpServletRequest request,HttpServletResponse response) throws IOException {
		Writer out = response.getWriter();
		response.setContentType("text/plain");
		try {
			if(!code.toLowerCase().equals(request.getSession().getAttribute("piccode").toString().toLowerCase())){
				out.write("0");//验证码不相同
			}else{
				out.write("1");
			}
		}catch(Exception e){
			// 报空指针异常，是因为2台服务器的问题，所以就提示下验证码错误。
			out.write("0");//验证码不相同
		}
		out.close();
	}
	/** 用户页面
	 * @throws IOException */
	@RequestMapping("/show")
	public String show(ModelMap model,CrmUserQuery query,HttpServletRequest request,HttpServletResponse response) throws IOException {
		model.addAttribute("cityList", CityManager.getAllCity());
		model.addAttribute("roleList",crmRoleManager.getAll());
		return "/sysmgr/user";
	}
	
	/** 用户列表 
	 * @throws IOException */
	@RequestMapping("/ajax/list")
	public void index(ModelMap model,CrmUserQuery query,HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		Writer out = response.getWriter();
		response.setContentType("text/plain");
		Gson gson = new Gson();
		setPagerModel(query,request);
		
		//query.setIsvalid(1);
		query.setUserCityNo(request.getParameter("searchUserCityNo"));
		String cityNo = getLoginUser(request).getCityNo();
		if((query.getUserCityNo() == null || "".equals(query.getUserCityNo())) && null != cityNo && !"".equals(cityNo)){
			query.setUserCityNo(cityNo.substring(1,cityNo.length()-1));
		}
		query.setRoleIds(request.getParameter("searchRole"));
		query.setUserName(request.getParameter("searchUserName"));
		
		@SuppressWarnings("unchecked")
		Page<CrmUser> page = crmUserManager.findPage(query);
		
		StringBuffer jsonbf = new StringBuffer();
		for(CrmUser temp:page.getResult()){
			System.out.println("getLastLoginTimeString="+temp.getLastLoginTimeString()+", temp.getLastLoginTime()="+temp.getLastLoginTime()+"  ");
		}
		jsonbf.append("{start:'" + query.getPageNumber() + "',limit:'" + query.getPageSize() + "',count:'" + page.getTotalCount() + "',root:");
		out.write(jsonbf.append(gson.toJson(page.getResult())).toString()+"}");
		out.close();
	}
	//新增或修改用户
	@RequestMapping(value = "/ajax/add")
	public void editUserInfo(ModelMap model,CrmUser entity,HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		Writer out = response.getWriter();
		//entity.setCityName(value);
		entity.setUserName(URLDecoder.decode(entity.getUserName(),"UTF-8"));
		entity.setUserTrueName(URLDecoder.decode(entity.getUserTrueName(),"UTF-8"));
		//entity.setRoleName();
		if(null == entity.getId() || entity.getId() <= 0){
			CrmUserQuery query = new CrmUserQuery();
			query.setUserName(entity.getUserName());
			//判断用户名是否重复
			if(crmUserManager.getBy(query).size() > 0){
				return;
			}
			entity.setUserPass("crmuser123456");//默认密码为 crmuser123456
			entity.setLastLoginTime(null);
			crmUserManager.save(entity);
		}else{
			crmUserManager.update(entity);
			//更新用户详细信息时，要更新 session 中的值
			String isWriteSession = request.getParameter("isWriteSession");
			if(null != isWriteSession && "true".equals(isWriteSession)){
				request.getSession().setAttribute(ProjectSetting.SESSION_USER_KEY,entity);
			}
			crmUserManager.removeFromCach(String.valueOf(entity.getId()));
		}
		writeMessage(out, 1);
	}
	//跳转至用户详细信息页面
	@RequestMapping("/userinfo")
	public String showUserInfo(ModelMap model,HttpServletRequest request,HttpServletResponse response){
		return "sysmgr/userinfo";
	}
	/** 批量删除用户
	 * @throws IOException */
	@RequestMapping(value = "/ajax/deleteByIds",method=RequestMethod.POST)
	public void deleteByIds(ModelMap model, String ids,HttpServletRequest request,HttpServletResponse response) throws IOException {
		Writer out = response.getWriter();
		response.setContentType("text/plain");
		if(null != ids){
			//crmUserManager.deleteByIds(ids);
			crmUserManager.updateByIds(ids);
			String[] idArray = ids.split(",");
			for(String userid:idArray){
				crmUserManager.removeFromCach(userid);
			}
			writeMessage(out, 1);
		}else{
			writeMessage(out, 0);
		}
	}
	/** 批量更新用户离职
	 * @throws IOException */
	@RequestMapping(value = "/ajax/updateByIds",method=RequestMethod.POST)
	public void updateByIds(ModelMap model, String ids,HttpServletResponse response) throws IOException {
		Writer out = response.getWriter();
		response.setContentType("text/plain");
		if(null != ids){
			crmUserManager.updateByIds(ids);
			String[] idArray = ids.split(",");
			for(String userid:idArray){
				crmUserManager.removeFromCach(userid);
			}
			writeMessage(out, 1);
		}else{
			writeMessage(out, 1);
		}
	}
	@RequestMapping("/ajax/getRoleById")
	public void getRoleById(HttpServletRequest request,String roleIds, HttpServletResponse response,
			ModelMap model) throws IOException{
		response.setCharacterEncoding("UTF-8");
		Writer out = response.getWriter();
		response.setContentType("text/plain");
		Gson gson = new Gson();
		List<CrmRole> list = crmRoleManager.getByIds(null == roleIds || "".equals(roleIds) ? "0" : roleIds.substring(1,roleIds.length() - 1));
		out.write("{\"options\":" + gson.toJson(list) + "}");
		out.close();
	}
	/** 根据用户id 更新用户角色
	 * @throws IOException */
	@RequestMapping(value = "/ajax/updateRoleIdsById",method=RequestMethod.POST)
	public void updateRoleIdsById(ModelMap model, String roleIds,String userId,HttpServletResponse response) throws IOException {
		Writer out = response.getWriter();
		response.setContentType("text/plain");
		if(null != roleIds && null != userId){
			crmUserManager.updateRoleIdsById(roleIds, userId);
			crmUserManager.removeFromCach(userId);
			writeMessage(out, 1);
		}else{
			writeMessage(out, 0);
		}
	}
	
	@RequestMapping("/ajax/ajaxgetyserbycityno")
	public void ajaxGetUserByCityno(HttpServletResponse response,int cityno){
		
			Map<String,Object>map = new HashMap<String,Object>();
			List<CrmUser> userList = crmUserManager.getUserListByCityno(cityno);
			map.put("data", userList);
			writeSuccessMessage(response);
	}
	/**
	 * 清空缓存的hashmap
	 */
	@RequestMapping("/refreshcah")
	public void refreshCach(HttpServletResponse response){
		writeSuccessMessage(response);
	}
	/**
	 * 清空缓存的hashmap
	 */
	@RequestMapping("/getcount")
	public void getcount(HttpServletResponse response){
		Map<String,Object> map = new HashMap<String,Object>();
		writeSuccessMessage(response,map);
	}
}

